<!-- 群发软文 -->
<template>
  <div  class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px; margin-bottom: 32px">
      <div class="content parameType">
        <div class="certification top">
        <div class="title">群发任务配置</div>
          <el-form label-width="120px">
            <el-col :xs="24" :sm="24" :lg="24">
              <!-- <el-form-item label="公司名称:">
                <el-input v-model="emailForm.CorpName"  style="width:300px"></el-input>
              </el-form-item> -->
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="公司网址:">
                <el-input v-model="emailForm.WebSite"  style="width:300px"></el-input>
              </el-form-item>
              <p>（系统会自动将邮件内容中的所有链接使用链接此网址）</p>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-button type="primary" @click="TestMailGlobal(emailForm)"  style="margin-left:700px">保存</el-button>
            </el-col>
          </el-form>
        </div>
      </div>
        <div class="title">目标邮箱</div>
        <div class="btn">
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addMailbox()">添加目标邮箱</el-button>
        </div>
        <el-table stripe border :data="mailboxList" style="width: 100%; margin-top: 15px">
          <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
          <el-table-column label="邮箱名称" prop="Descp" align="left" width="240px"></el-table-column>
          <el-table-column label="邮箱数量" prop="AccountCount" align="left"  width="100px"></el-table-column>
          <el-table-column label="资源标识" show-overflow-tooltip prop="FileID" align="left"></el-table-column>
          <el-table-column label="操作" align="left" width="180px">
            <template slot-scope="scope">
              <el-button size="mini" @click="checkMailGlobal(scope.row)">查看</el-button>
              <el-button size="mini" type="danger" @click="deleteMailGlobal(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="title" style="margin-top:20px">邮件内容</div>
        <div class="btn">
          <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addResources()">添加邮件内容</el-button>
        </div>
        <el-table stripe border :data="contentOfEmail" style="width: 100%; margin-top: 15px">
          <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
          <el-table-column label="邮件标题" show-overflow-tooltip prop="Title" align="left" width="120px"></el-table-column>
          <el-table-column label="邮件正文尺寸" show-overflow-tooltip prop="size" width="120px" align="left"></el-table-column>
          <el-table-column label="审核状态" align="left" width="100px">
            <template slot-scope="scope">
              <p style="color:#909399" v-if="scope.row.Status === 0" type="info">等待审核</p>
              <p style="color:#67C23A" v-if="scope.row.Status === 1" type="success">审核成功</p>
              <p style="color:#F56C6C" v-if="scope.row.Status === 2" type="danger">审核拒绝</p>
            </template>
          </el-table-column>
          <el-table-column label="备注信息" prop="Descp" align="left"></el-table-column>
          <el-table-column label="操作" align="left" width="180px">
            <template slot-scope="scope">
              <el-button size="mini" @click="changeMailCount(scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="deleteMailcontent(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
    </el-row>
    <el-dialog title="目标邮箱" :close-on-click-modal="false" :close-on-press-escape=false :visible.sync="emaildialog" v-el-drag-dialog width="50%">
      <el-input v-model="emaliList" type="textarea" :autosize="{ minRows: 15, maxRows:25}"></el-input>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape=false title="网络图片" :visible.sync="imgdialog" v-el-drag-dialog width="500px">
      <el-select v-model="webImgurl" style="width:100%;margin-bottom: 10px;">
        <el-option v-for="(item, index) in webImgList" :key="index" :value="item.URL" :label="item.Descp"></el-option>
      </el-select>
      <img :src="webImgurl" style="width:100%"  :alt="webImgurl">
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="choseImg()">确 定</el-button>
        <el-button type="info" @click="imgdialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      :title="Action === 1 ? '添加目标邮箱' : '查看目标邮箱' "
      :visible.sync="dialogVisible"
      v-el-drag-dialog
      width="800px">
      <el-form label-width="100px" :model="resourceForm" ref="resourceForm">
        <el-form-item label='邮箱名称:'>
          <el-input type="texteart" v-model="resourceForm.remark" maxlength="16"></el-input>
        </el-form-item>
        <!-- <el-form-item label='导入文件:'>
          <el-upload
            class="upload-demo"
            action="#"
            multiple
            accept=".txt"
            ref="upload"
            :disabled="Action !== 1"
            :on-change="filechange"
            :http-request="mailfileCllick"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">点击导入</el-button>
          </el-upload>
        </el-form-item> -->
        <el-form-item label='资源内容:'>
          <!-- <el-input type="textarea" v-model="resourceForm.resourceContent" :autosize="{ minRows: 5, maxRows:10}"></el-input> -->
        <div style="display:flex; justify-content:flex-end;background:#f5f6fa;padding:10px;border: 1px solid #D3D5E0;">
            <el-upload
            class="upload-demo"
            action="#"
            multiple
            accept=".txt"
            ref="upload"
            :disabled="Action !== 1"
            :on-change="filechange"
            :http-request="mailfileCllick"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :show-file-list=false
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">点击导入</el-button>
          </el-upload>
        </div>
        <div class="key-word-textarea flex">
          <div class="text-area-num-scroll">
            <div class="text-area-num-box" ref="textAreaNumBox" @scroll="sysHandleScroll()">
              <div v-for="(t,i) in rowNum" :key="i" class="text-area-num"><span>{{i+1}}</span></div>  <!-- :style="{color:errMail.includes(i) ? 'red' : ''}" -->
              <!-- <div v-for="(t,i) in textAreaNum" :key="i" class="text-area-num"><span>{{i+1}}</span></div> -->
            </div>
          </div>
          <el-input
            id="text"
            ref="text"
            type="textarea"
            :autosize="{ minRows: 10, maxRows: 10}"
            :placeholder="'文件中每行对应一个邮箱'"
            v-model="resourceForm.resourceContent"
            resize="none"
            @input="handleInputText">
          </el-input>
        </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :close-on-press-escape=false
      top="5vh"
      :title="Action === 1 ? '添加邮件通知任务' : '查看邮件通知任务' "
      :visible.sync="maildialog"
      v-el-drag-dialog
      :close-on-click-modal = false
      width="60%">
      <el-form label-width="120px" :model="contentForm" :rules="rules" ref="resourceForm">
        <el-form-item label='邮件标题:' prop="Title">
          <el-input v-model="contentForm.Title" maxlength="32"></el-input>
        </el-form-item>
        <el-form-item label='邮件内容:' prop="ContentHtml">
          <el-tabs type="border-card" class="tabs">
            <el-tab-pane label="编辑邮件">
              <editor-bar
                :value="editorhtml"
                :link="contentForm.link"
                v-model="ContentHtml"
                @change="editorchange"
                @fileclick="fileclick"
                @imgdialogopen="imgdialogopen"
                :rows="2"
                ref="editor"
              ></editor-bar>
              <input style="display:none" type="file" ref="filetemplete" @change="filetempleteChange($event)" accept=".html,.txt">
            </el-tab-pane>
            <!-- <el-tab-pane label="自定义邮件">
              <el-button @click="$refs.filetemplete.click()">邮件上传</el-button>
            </el-tab-pane> -->
            <el-tab-pane label="查看源码">
              <el-input
                type="textarea"
                :rows="18"
                @blur="changesourceCode()"
                placeholder="请输入内容"
                v-model="sethtml">
              </el-input>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
        <el-form-item label='备注:'>
          <el-input type="texteart" v-model="contentForm.Descp"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sendContent()">确 定</el-button>
        <el-button type="info" @click="maildialog = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { connrequest } from '@/api/firstPage'
import { getuuid, bytesToSize, parseTime } from '@/utils/index'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import EditorBar from '@/components/EditorBar'
export default {
directives: { elDragDialog },
components: { EditorBar },
data() {
  return {
    textAreaNum: [''],
    errMail:[],
    pageNum: 1,
    pageSize: 10,
    total: 10,
    mailboxList:[],
    contentOfEmail:[],
    emailForm: {},
    emailList: [],
    fileList: [],
    emaliList:[],
    webImgList:[],
    webImgurl: '',
    webImglink:'',
    dialogVisible: false,
    emaildialog: false,
    maildialog: false,
    imgdialog: false,
    resourceForm: {
      file:'',
      remark:'',
      resourceContent:`
      `
    },
    contentForm: {},
    editorhtml: '',
    ContentHtml: '',
    sethtml:'',
    Action: 1,
    rowNum: 1,
    rules: {
      Name:[
        { required: true, message: "请选择接收对象"}
      ],
      CreateTime:[
        { required: true, message: "请选择创建时间"}
      ],
      Title:[
        { required: true, message: "请输入邮件标题"}
      ],
    },
  }
},
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
    this.getwebImg()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  watch: {
    textAreaNum: {
      handler(newValue, oldValue) {
        this.textAreaNum = newValue.toString()
        this.rowNum = this.textAreaNum.split(',').length
      },
      deep: true
    }
  },
  methods: {
    sysHandleScroll() {
      this.$nextTick(() => {
        const textarea = document.getElementById('text');
        textarea.scrollTop = this.$refs.textAreaNumBox.scrollTop
      })
    },
    async getwebImg(){
      const res = await connrequest('GetEMailResList')
      res.Data = res.Data || []
      res.Data.map(item => {
        item.CreateTime = parseTime(item.CreateTime)
        return item
      })
      this.webImgList = res.Data
    },
    handleInputText(val){
        this.textAreaNum = this.resourceForm.resourceContent.split("\n")
    },
    imgdialogopen(){
      this.webImgurl = ''
      this.webImglink = ''
      this.imgdialog = true
    },
    editorchange(val){
      this.editorhtml = val
      this.sethtml = val
    },
    choseImg(){
      if(this.webImgurl === ''){
        this.$message.error('请选择图片')
        return false
      }
      this.$refs.editor.insertImg(this.webImgurl);
      this.imgdialog = false
    },
    querySearch(queryString, cb) {
      var restaurants = this.emailList;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    async TestMailGlobal(row){
      const data = {
        Data: {
          WebSite: row.WebSite,
          CorpName: row.CorpName
        }
      }
      const res = await connrequest('SetEMailTaskADBasic', data)
      if(res.Status.StatusCode === 0){
        this.$message.success('保存成功')
      }
    },
    deleteMailGlobal(row){
      this.Action = 3
      this.resourceForm = {...row}
      this.$confirm('此操作将删除该邮箱, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = {
          Data:{
            Action: this.Action,
            Detail: {
              ...this.resourceForm
            }
          }
        }
        const res = await connrequest('EditEMailTaskADToAccounts', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('删除成功')
          this.dialogVisible = false
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    async getData() {
      const res = await connrequest('GetEMailTaskAD')
      this.emailForm = res.Data
      if(res.Data.Subject){
        res.Data.Subject.forEach(item => {
          item.Title = Buffer.from(item.Title, 'base64').toString('utf8')
          item.size = bytesToSize(item.ContentHtml.length)
        })
      }
      res.Data.ToAccount.map(item => {
        let arr = Buffer.from(item.Accounts, 'base64').toString('utf8').split('\n')
        item.AccountCount = arr.filter(Boolean).length || 0
        return item
      })
      this.mailboxList = res.Data.ToAccount || []
      this.contentOfEmail = res.Data.Subject || []
    },
    checkMailGlobal(row){
      this.emaildialog = true
      let Accounts = Buffer.from(row.Accounts, 'base64').toString('utf8')
      this.emaliList = Accounts
    },
    filechange(file, fileList){
      let arr = []
      fileList.map(item => {
        arr.push({FileName: item.name, InnerName: item.uid + ''})
      })
      this.Attach = arr
    },
    // 添加目标邮箱
    addMailbox(){
      this.Action = 1
      this.dialogVisible = true
      this.textAreaNum = [''],
      this.errMail = [],
      this.$nextTick(()=>{
        this.$refs.upload.clearFiles()
        this.resourceForm = {}
        let vm = this
        // 带行号的文本框
        document.querySelector('textarea').addEventListener("scroll",function () {
          vm.$refs.textAreaNumBox.scrollTop = this.scrollTop
        },false);
        console.log(this.textAreaNum);
      })
    },
    // 目标邮箱文件上传
    mailfileCllick(file){
      const istxt = file.file.type === 'text/plain';
      if(!istxt){
        this.$message.error('只能上传.txt文件')
        this.$refs.upload.clearFiles()
        this.resourceForm = {}
        return false
      }
      let fileData = file.file
      let reader = new FileReader();
      // 传入一个参数对象即可得到基于该参数对象的文本内容
      reader.readAsDataURL(fileData);
      reader.onload = (e) => {
        // target.result 该属性表示目标对象的DataURL
        let file = e.target.result.split(',')[1]  //去掉文件类型
        let resourceContent = Buffer.from(file, 'base64').toString('utf8')
        resourceContent = resourceContent.replace(/(\n[\s\t]*\r*\n)/g, '\n').replace(/^[\n\r\n\t]*|[\n\r\n\t]*$/g, '')
        this.$set(this.resourceForm, 'resourceContent', resourceContent);
        this.textAreaNum = resourceContent.split('\r\n').toString()
        this.fileList = []
        // this.$set(this.resourceForm, 'file', file)
      }
    },
    async handleRemove(file, fileList) {
      const data = {
        Data:{
          InnerName: file.uid
        }
      }
      const res = await connrequest('DeleteEMailAttach', data)
      if(res.Status.StatusCode === 0){
        this.$message.success('文件删除成功')
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    async submit(){
      if(!this.resourceForm.resourceContent){
        this.$message.error('资源内容不能为空')
      }
      else if(!this.resourceForm.remark){
        this.$message.error('请填写邮箱名称')
      }else{
        let val = this.resourceForm.resourceContent.replace(/(\n[\s\t]*\r*\n)/g, '\n').replace(/^[\n\r\n\t]*|[\n\r\n\t]*$/g, '')
        this.textAreaNum = this.textAreaNum.replace(/(\n[\s\t]*\r*\n)/g, '\n').replace(/^[\n\r\n\t]*|[\n\r\n\t]*$/g, '')
        let textAreaNum = this.textAreaNum.split(',').filter(d=>d)
        let email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
        let errMail = []
        textAreaNum.map((item,i) => {
          if(!email.test(item)){
            errMail.push(i)
          }
        })
        this.errMail = errMail
        this.$set(this.resourceForm, 'resourceContent', val);
        if(this.errMail.length > 0){
          this.$message.error(`检测到 ${textAreaNum.length } 条正常目标邮件，部分不符合邮件规范的条目 ${this.errMail.length} 条被系统自动剔除`)
          return false
        }
        if(!this.resourceForm.resourceContent){
          this.$message.error('资源内容不能为空')
          return false
        }
        const data = {
          Data:{
            Action: this.Action,
            Detail:{
              FileID: getuuid(),
              Accounts: Buffer.from(this.resourceForm.resourceContent, 'utf-8').toString('base64'),
              Descp: this.resourceForm.remark
            }
          }
        }
        const res = await connrequest('EditEMailTaskADToAccounts', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('添加成功')
          this.dialogVisible = false
          this.getData()
          this.$nextTick(()=>{
            this.$refs.upload.clearFiles()
          })
        }
      }
    },
    // 添加邮件内容
    addResources(){
      this.Action = 1
      this.maildialog = true
      this.$nextTick(()=>{
        this.contentForm = {}
        this.$refs.editor.clearText()
        this.$refs['resourceForm'].resetFields()
      })
    },
    // 导入自定义邮件
    filetempleteChange(e){
      let file = e.target.files[0]
      if(file.name.indexOf("html") < 0 && file.name.indexOf("txt") < 0){
        this.$message.error('请选择html格式或txt格式的文件')
        this.$refs.filetemplete.value = ''
        return false
      }
      // FileReader对象，h5提供的异步api，可以读取文件中的数据。
      const reader = new FileReader()
      // readAsText是个异步操作，只有等到onload时才能显示数据。
      reader.readAsText(file)
      reader.onload = () => {
        //当读取完成后回调这个函数,然后此时文件的内容存储到了result中
        this.sethtml = reader.result
        this.$refs.editor.sethtml(this.sethtml)
        this.$refs.filetemplete.value = ''
      }
    },
    // 添加群发内容
    async sendContent(){
      this.$refs['resourceForm'].validate(async (valid) => {
        if(valid){
          if(this.ContentHtml === ''){
            this.$message.error('请输入邮件内容')
            return false
          }
          if(this.Action === 1){
            let html = `
            <!doctype html>
            <html lang="en">
            <head>
              <meta charset="UTF-8">
              <meta http-equiv="X-UA-Compatible" content="IE=edge">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <title>Document</title>
            </head>
            <body>
              ${this.ContentHtml}
            </body>
            <style>
              *{
                margin: 0
                padding: 0
              }
              img{
                vertical-align:left;
                display:block;
              }
            </style>
            </html>`
            const data = {
              Data:{
                Action: 1,
                Detail:{
                  Status: 0,
                  SubjectID: getuuid(),
                  Title: Buffer.from(this.contentForm.Title, 'utf-8').toString('base64'),
                  Descp: this.contentForm.Descp,
                  ContentHtml: Buffer.from(html, 'utf-8').toString('base64')
                }
              }
            }
            const res = await connrequest('EditEMailTaskADSubject', data)
            if(res.Status.StatusCode === 0){
              this.$message.success('添加邮件内容成功')
              this.maildialog = false
              this.getData()
            }
          }else{
            this.changeMailCountSubmit()
          }
        }
      })
    },
    // 修改
    async changeMailCount(row){
      this.Action = 2
      this.ContentHtml = Buffer.from(row.ContentHtml, 'base64').toString('utf8')
      this.contentForm = {...row}
      this.maildialog = true
      this.$nextTick(()=>{
        this.editorhtml = row.Subject
        this.$refs.editor.updateText()
        // this.$refs.upload.clearFiles()
      })
    },
    // 修改提交
    async changeMailCountSubmit(){
      const data = {
        Data:{
          Action: 2,
          Detail:{
            Status: 0,
            SubjectID: this.contentForm.SubjectID,
            Title: Buffer.from(this.contentForm.Title, 'utf-8').toString('base64'),
            Descp: this.contentForm.Descp,
            ContentHtml: Buffer.from(this.ContentHtml, 'utf-8').toString('base64')
          }
        }
      }
      const res = await connrequest('EditEMailTaskADSubject', data)
      if(res.Status.StatusCode === 0){
        this.$message.success('添加邮件内容成功')
        this.maildialog = false
        this.getData()
      }
    },
    async deleteMailcontent(row){
      this.$confirm('此操作将删除该任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = {
          Data:{
            Action: 3,
            Detail: {
              ...row
            }
          }
        }
        const res = await connrequest('EditEMailTaskADSubject', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('删除成功')
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    fileclick(){
      this.$refs.filetemplete.click()
    },
    async uploadFile(file){
      let formData = new FormData();
      formData.append('CmdCode', "UploadEMailAttatch");
      formData.append('FileName', file.file.name);
      formData.append('InnerName', file.file.uid);
      formData.append('file', file.file);
      formData.append('Token', getToken());
      const res = await uploadfile('UploadEMailAttatch',formData)
      if(res.Status.StatusCode === 0) {
        this.$message.success('文件上传成功')
      }
    }
  }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
@import "~@/styles/variables.scss";
.content {
  margin-top: 0;
  width: 800px;
  position: relative;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .title{
    margin-bottom: 10px;
  }
  ::v-deep .certification{
    .el-form-item{
      margin-bottom: 10px;
    }
    .el-col{
      display: flex;
      align-items: center;
      p{
        width: 100px;
        display:block;
        color: #aaa;
        font-size: 12px;
        padding-left: 20px;
        white-space: nowrap;
      }
    }
  }
}
.top{
  flex-wrap: nowrap;
}
.btn{
  margin: 20px 0;
}



.key-word-textarea {
  height: 170px;
  overflow: hidden;
  box-shadow: 0px -1px 5px 0px rgba(220, 229, 255, 0.7);
  border: 1px solid #D3D5E0;
  border-top: none;
  align-items: flex-start;
  .el-textarea ::v-deep {
    .el-textarea__inner {
      border: none;
      border-radius: 0;
      line-height: 20px;
      font-size: 14px;
      height: 172px !important;
      min-height: 172px !important;
    }
  }
}


.text-area-num-scroll {
  width: 80px;
  overflow: hidden;
  height: 180px;
  background: #F5F6FA;
  padding-top: 5px;
}
.text-area-num-box {
  min-height: 172px;
  overflow-y: auto;
  height: 172px;
  width: 70px;
  padding-bottom: 10px;
}
.text-area-num {
  line-height: 20px;
  width: 50px;
  text-align: center;
}
.flex {
  display: flex;
}

</style>